package sms.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import sms.entity.Course;
import sms.service.CourseService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addCourse(Course course) {
        String sql="insert into course values(?,?)";
        jdbcTemplate.update(sql,course.getCourse_id(),course.getCourse_name());
    }

    @Override
    public void deleteCourse(String id) {
        String sql="delete from course where course_id=?";
        jdbcTemplate.update(sql,id);
    }

    @Override
    public List<Course> getCourseList(String str) {
        String sql="select * from course";
        List<Object> params = new ArrayList<Object>();
        if(str!=null&&!str.trim().isEmpty()){
            sql="select * from course where course_name like ?";
            params.add("%"+str+"%");
        }
        return jdbcTemplate.query(sql, params.toArray(), new RowMapper<Course>(){
            @Override
            public Course mapRow(ResultSet rs, int rowNum) throws SQLException {
                Course course=new Course();
                course.setCourse_id(rs.getString("course_id"));
                course.setCourse_name(rs.getString("course_name"));
                return course;
            }
        });
    }

    @Override
    public void updateCourse(Course course) {
        String sql="update course set course_name=? where course_id=?";
        jdbcTemplate.update(sql,course.getCourse_name(),course.getCourse_id());
    }

    @Override
    public Course getCourse(String id) {
        String sql="select * from course where course_id=?";
        return jdbcTemplate.queryForObject(sql,(rs, rowNum) ->{
            Course course=new Course();
            course.setCourse_id(rs.getString("course_id"));
            course.setCourse_name(rs.getString("course_name"));
            return course;
        },id );
    }
}